//****************针对第二种方式的具体js实现部分******************//
//****************所使用的数据是city.js******************//
/*根据id获取对象*/
//var serUrl = 'http://192.0.11.154:80'
var serUrl = window.location.origin
var serIDs = ''
function ById(str) {
    return document.getElementById(str);
}
var selectCityModal = ById('selectCityModal');  //最终地址显示框
var addrShow02 = ById('companyAddress');  //最终地址显示框
var titleWrap = ById('title-wrap').getElementsByTagName('DD');
var addrWrap = ById('addr-wrap');   //省市区显示模块
var btn2 = document.getElementsByClassName('met2')[0];  //确定按钮
var isEmail = true
var isTel = true


function showSelectCityModal() {
    selectCityModal.style.display = 'inline-block'
    showProv2()
}

function hideSelectCityModal() {
    selectCityModal.style.display = 'none'
}

var current2 = {
    prov: '',
    city: '',
    country: '',
    provVal: '',
    cityVal: '',
    countryVal: '',
	id:'',
};

/*自动加载省份列表*/
/*window.onload = showProv2();*/

function showProv2() {
    addrWrap.innerHTML = '';
    btn2.disabled = true;
    titleWrap[0].className = 'titleSel';
    var len = provice.length;
    for (var i = 0; i < len; i++) {
        var provLi = document.createElement('dd');
        provLi.innerText = provice[i]['name'];
        provLi.id = 'pro'+provice[i]['code'];
        provLi.index = i;
        addrWrap.appendChild(provLi);
    }
	setTimeout(function(){
		if(current2.id.length >0){
		var curpro = document.getElementById(current2.id.substr(0,5))
		if(curpro){
			curpro.className = 'selectLi'
		}
	}
	},0)
}

/*************************需要给动态生成的li绑定点击事件********************** */
addrWrap.onclick = function (e) {
    var n;
    var e = e || window.event;
    var target = e.target || e.srcElement;
	target.className = 'curSel'
    if (target && target.nodeName === 'DD') {
        /*先判断当前显示区域显示的是省市区的那部分*/
        for (var z = 0; z < 3; z++) {
            if (titleWrap[z].className === 'titleSel')
                n = z;
        }
        /*显示的处理函数*/
        switch (n) {
            case 0:
                showCity2(target.index);
                break;
            case 1:
                showCountry2(target.index);
                break;
            case 2:
                selectCountry(target.index);
                break;
            default:
                showProv2();
        }
    }
	current2.id = target.id
};

/*选择省份之后显示该省下所有城市*/
function showCity2(index) {
    addrWrap.innerHTML = '';
    current2.prov = index;
    current2.provVal = provice[index].name;
    titleWrap[0].className = '';
    titleWrap[1].className = 'titleSel';
    var cityLen = provice[index].children.length;
    for (var j = 0; j < cityLen; j++) {
        var cityLi = document.createElement('dd');
        cityLi.innerText = provice[index].children[j].name;
		cityLi.id = 'pro'+provice[index].children[j].code;
        cityLi.index = j;
        addrWrap.appendChild(cityLi);
    }
	setTimeout(function(){
		if(current2.id.length >0){
		var curpro = document.getElementById(current2.id.substr(0,7))
		if(curpro){
			curpro.className = 'selectLi'
		}
	}
	},0)
}

/*选择城市之后显示该城市下所有县区*/
function showCountry2(index) {
    addrWrap.innerHTML = '';
    current2.city = index;
    current2.cityVal = provice[current2.prov].children[index].name;
    titleWrap[1].className = '';
    titleWrap[2].className = 'titleSel';
    var countryLen = provice[current2.prov].children[index].children.length;
    if (countryLen === 0) {
        addrShow02.value = current2.provVal + '-' + current2.cityVal;
    }
    for (var k = 0; k < countryLen; k++) {
        var cityLi = document.createElement('dd');
        cityLi.innerText = provice[current2.prov].children[index].children[k].name;
        cityLi.id = 'pro'+provice[current2.prov].children[index].children[k].code;
        cityLi.index = k;
        addrWrap.appendChild(cityLi);
    }
}

/*选中具体的县区*/
function selectCountry(index) {
    btn2.disabled = false;
    current2.country = index;
    var list = addrWrap.getElementsByTagName('dd')
    for (var i = 0; i < list.length; i++) {
        list[i].style.backgroundColor = '';
    }
    addrWrap.getElementsByTagName('dd')[index].style.backgroundColor = '#23B7E5';
    current2.countryVal = provice[current2.prov].children[current2.city].children[index].name;
	//addrShow02.value = current2.provVal + ' ' + current2.cityVal + ' ' + current2.countryVal;
    //addrWrap.getElementsByTagName('dd')[current2.country].style.backgroundColor = '';
}

/*点击确定后恢复成初始状态，且将所选地点显示在输入框中*/
btn2.onclick = function () {
    addrShow02.value = current2.provVal + '-' + current2.cityVal + '-' + current2.countryVal;
    addrWrap.getElementsByTagName('dd')[current2.country].style.backgroundColor = '';
	current2.id = ''
	titleWrap[2].className = '';
    titleWrap[0].className = 'titleSel';
	showProv2();
    hideSelectCityModal();
};

/*分别点击省市区标题的处理函数*/
document.getElementById('title-wrap').onclick = function (e) {
    var e = e || window.event;
    var target = e.target || e.srcElement;
    if (target && target.nodeName === 'DD') {
        for (var z = 0; z < 3; z++) {
            titleWrap[z].className = '';
        }
        target.className = 'titleSel';
        if (target.id === 'ck0') {
            showProv2();
        } else if (target.id === 'ck1') {
            showCity2(current2.prov);
        } else {
            showCountry2(current2.city);
        }
    }
};

document.getElementById('contact').onblur = function(e){
    var e = e || window.event;
    var target = e.target || e.srcElement;
    var newVal = '';
    newVal = target.value.replace(/[`~!@#$%^&*()+_=|{}':;.'"",\[\]<>/?~！@#￥%……&*（）——+|{}【】《》 ‘；：”“’。，、？]/ig, '');
    newVal = newVal.replace(/\s+/ig, '');
    if (newVal.length > 30) {
        newVal = newVal.substring(0, 30)
    }
    document.getElementById('contact').value = newVal
}
document.getElementById('companyName').onblur = function(e){
    var e = e || window.event;
    var target = e.target || e.srcElement;
    var newVal = '';
    newVal = target.value.replace(/[`~!@#$%^&*()+_=|{}':;.'"",\[\]<>/?~！@#￥%……&*（）——+|{}【】《》 ‘；：”“’。，、？]/ig, '');
    newVal = newVal.replace(/\s+/ig, '');
    if (newVal.length > 30) {
        newVal = newVal.substring(0, 30)
    }
    document.getElementById('companyName').value = newVal
}
document.getElementById('appUsage').onblur = function(e){
    var e = e || window.event;
    var target = e.target || e.srcElement;
    var newVal = '';
    newVal = target.value.replace(/[`~!@#$%^&*()+_=|{}':;'""\[\]<>/?~！@#￥%……&*（）——+|{}【】《》 ‘；：”“’、？]/ig, '');
    newVal = newVal.replace(/\s+/ig, '');
    if (newVal.length > 200) {
        newVal = newVal.substring(0, 200)
    }
    document.getElementById('appUsage').value = newVal
}

document.getElementById('email').onblur = function(e){
    var e = e || window.event;
    var target = e.target || e.srcElement;
    var reg = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/
    var value = target.value
    if (!reg.test(value)) {
        ngTip.tip ('请输入正确的邮箱格式', 'warning')
        document.getElementById('email').style.color='red'
        isEmail = false
    } else if (value.length > 40) {
        ngTip.tip ('邮件地址不能超过40位', 'warning')
        isEmail = false
        document.getElementById('email').style.color='red'
    }else {
        isEmail = true
        document.getElementById('email').style.color=''
    }
}

document.getElementById('phone').onblur = function(e){
    var e = e || window.event;
    var target = e.target || e.srcElement;
    var value = target.value
    var res3 = /^1[3|4|5|6|7|8|9][0-9]{9}$/
    var res4 = /0\d{2,3}-\d{7,8}$/
    if (!(res3.test(value) || res4.test(value))) {
        ngTip.tip ('请输入合法联系方式', 'warning')
        isTel = false
        document.getElementById('phone').style.color='red'
    } else {
        isTel = true
        document.getElementById('phone').style.color=''
    }
}



/*tijiao*/
document.getElementById('submit-button').onclick = function (e) {
    var list = document.getElementsByTagName('input')
    var prams = {}
    for (var i = 0; i < list.length; i++) {
        if (list[i].value === '') {
            ngTip.tip(list[i].placeholder, 'warning')
            break;
            return
        }
        prams[list[i].id] = list[i].value
    }

    var appUsage = ById('appUsage')
    if (appUsage.value === '') {
        ngTip.tip('请输入AASTU随机数用途', 'warning')
        return
    }
    prams.appUsage = appUsage.value
    prams.verifyId = serIDs
    if (!isTel) {
        ngTip.tip('请输入合法联系方式', 'warning')
        return
    }
    if (!isEmail) {
        ngTip.tip('请输入正确的邮箱格式', 'warning')
        return
    }

    var imgcode = ById('verifyCode')
    if(imgcode.value.length !== 4){
        ngTip.tip('请输入正确的验证码', 'warning')
        return
    }
    prams.companyAddress = prams.companyAddress.replace(/-/g,',')
    $.ajax({
        url:serUrl+'/qrmc/userexternal/registerBusinessUserExternal',    //此处连接地址可变更
        type: 'post',
        data: JSON.stringify(prams),
        contentType:"application/json;charset=UTF-8",
        dataType:"json",
        async: true,
        crossDomain: true === !(document.all),
        success: function (response) {
            if(response.code === 0 ){
                ngTip.tip('注册成功，请注意接收邮件', 'success')
                ById('contact').value = ''
                ById('phone').value = ''
                ById('email').value = ''
                ById('companyAddress').value = ''
                ById('companyName').value = ''
                ById('appUsage').value = ''
            }else{
                ngTip.tip(response.message, 'warning')
            }
            getVerifyCode()
            ById('verifyCode').value = ''
        },
        error:function ( response ) {
            ngTip.tip('请求失败', 'warning')
        }
    })
}


getVerifyCode()
document.getElementById('imgcode').onclick = function (e){
    getVerifyCode()
}
function getVerifyCode(){
    $.ajax({
        url:serUrl+'/qrmc/userexternal/getVerifyCodeExternal',    //此处连接地址可变更
        type: 'GET',
        data:'',
        contentType:"application/json;charset=UTF-8",
        dataType:"json",
        crossDomain: true,
        success: function (response) {
            if(response.code === 0 ){
                serIDs = response.data.verifyId
                document.getElementById('imgcode').style.backgroundImage = 'url(data:image/jpeg;base64,' + response.data.verifyCodeBase64 + ')'
            }else{
                ngTip.tip(response.message, 'warning')
                serIDs=''
            }
        },
        error:function ( response ) {
            ngTip.tip('请求失败', 'warning')
        }
    })
}


function getSessionId() {
    var c_name = 'JSESSIONID'
    console.log(document.cookie)
    if(document.cookie.length> 0){
        var c_start =document.cookie.indexOf(c_name+'=')
        if(c_start !== -1){
            c_start = c_start+ c_name.length + 1
            var c_end = document.cookie.indexOf(';',c_start)
            if(c_end === -1){
                c_end = document.cookie.length
            }
            return unescape(document.cookie.substring(c_start,c_end))
        }else{
            return ById('sessionId').value
        }
    }
}
